// pages/exam/examLoading/examLoading.js
var app = getApp();
var config = require('../../../config.js');
var c = 0
var totalTime = 3;
var t;
var examInfo;


Page({

  /**
   * 页面的初始数据
   */
  data: {
    time: totalTime
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.fromType == 2){
      //考试结束 计算成绩
      var examId = options.examId
      console.log("examId==" + examId);
      this.setData({
        examId: examId,
        time: "正在计算成绩...",
        fromType : 2
      })

    }else{
      var examId = options.examId
      console.log("examId==" + examId);
      this.setData({
        examId: examId,
        time: totalTime
      })
      //请求题库数据
      this.initData();

    }

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(this.data.fromType == 2){
      setTimeout(function(){
        wx.redirectTo({
          url: '../examResult/examResult?fromType=1'
        })

      },3000);
     
    }else{
      c = 0;
      this.setData({
        time: totalTime
      })
      this.timedCount();
    }
    
  },

  initData: function () {
    var that = this;
    wx.request({
      url: config.getExamQuesList,
      method: "POST",
      data: {
        examId: that.data.examId
      },
      success: function (ret) {
        var data = ret.data
        if (data.success == 0) {
          examInfo = data.rows;
          if (examInfo) {
            //存入到Storage中 避免大数量传递问题
            try {
              wx.setStorageSync(config.examList, examInfo)
              //
            } catch (e) {
             }
          }
        }else{
          //获取考题失败
          wx.showToast({
            title: '服务器出错啦！',
            icon: "none"
          })
        }
      }
    })
  },

  timedCount: function () {
    var that = this;
    t = setTimeout(function () {
      c = c + 1
      that.setData({
        time: (totalTime - c) == 0 ? "考试开始" : totalTime - c
      });
      if ((totalTime - c) == 0) {
        that.stopCount();
        c = 0;
      } else {
        that.timedCount();
      }

    }, 1000)



  },

//时间到 停止任务
  stopCount: function () {
    var that = this;
    clearTimeout(t)
    console.log("定时器停止工作了");

    if (examInfo) {
      setTimeout(function(){
        wx.redirectTo({
          url: '../examGoing/examGoing?examId=' + that.data.examId
        },3000);
      })
     
    } else {

      that.setData({
        time: "0"
      });
      //间隔1.5 再次重试
      setTimeout(function () {
        if (examInfo) {
          wx.redirectTo({
            url: '../examGoing/examGoing?examId=' + that.data.examId
          })
        }
      }, 1500);
    }

  }

})